import { createRef, RefObject } from 'react'
import { Result } from 'ahooks/lib/useRequest/src/types'
import { create } from 'zustand'
import { AgGridReact } from '@ag-grid-community/react'

import { DEFAULT_PAGE_SIZE } from '@/utils/pagination'
import { AllPublishPathODTO, IEventListPublishPathListReq, IEventListPublishPathListRes } from './interface'
import { normalizeReqData } from './utils'

export type TRequest = Result<IEventListPublishPathListRes, [IEventListPublishPathListReq]>

interface IStore {
  gridRef: RefObject<AgGridReact<AllPublishPathODTO>>
  request?: TRequest
  reqData: IEventListPublishPathListReq
  setReqData: (
    val:
      | Partial<IEventListPublishPathListReq>
      | ((prevVal: IEventListPublishPathListReq) => IEventListPublishPathListReq),
  ) => void
  getData: (scrollToTop?: boolean) => void
}

export const defaultParams = {
  page: 1,
  size: DEFAULT_PAGE_SIZE,
  visibleFlag: undefined,
  shipTrackRequire: undefined,
  searchField: undefined,
  searchWords: undefined,
  customerIds: undefined,
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    gridRef: createRef(),
    reqData: { ...defaultParams },
    setReqData: val => {
      set(prev => {
        return {
          reqData: {
            ...prev.reqData,
            ...(typeof val === 'function' ? val(prev.reqData) : val),
          },
        }
      })
    },
    getData: scrollToTop => {
      const { gridRef, request, reqData } = get()
      request?.run(normalizeReqData(reqData))
      if (scrollToTop) gridRef.current?.api?.ensureIndexVisible(0, 'top')
    },
  }
})
